package io.easyspring.demo.basis.rbac.service.impl;

import io.easyspring.demo.basis.rbac.model.User;
import io.easyspring.demo.basis.rbac.mapper.UserMapper;
import io.easyspring.demo.basis.rbac.service.UserService;
import io.easyspring.framework.base.service.impl.BaseServiceImpl;
import io.easyspring.framework.base.service.impl.ExtensionBaseServiceImpl;
import io.easyspring.framework.common.exception.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Pageable;
import com.github.pagehelper.Page;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import javax.annotation.Resource;

/**
 * 用户对象 服务实现类
 *
 * @author summer
 * @version 2.0.0-RELEASE
 * DateTime 2019-10-15 15:15:03
 */
@Service
@Slf4j
public class UserServiceImpl extends ExtensionBaseServiceImpl<UserMapper, User>
        implements UserService {

    /**
     * 注入用户对象的 mapper
     */
    @Resource
    private UserMapper userMapper;

    /**
     * 添加用户的方法
     *
     * @param user 用户对象
     * @return io.easyspring.demo.basis.rbac.model.User
     * Author summer
     * Version 2.0.0-RELEASE
     * DateTime 2019-10-15 15:29
     */
    @Override
    public User buildSave(User user) {

        // 检查用户名是否已经存在
        boolean valueExist = valueExist(User::getName, user.getName(), User.class);
        // 如果用户名已经存在
        if (valueExist) {
            throw new CommonException("用户名已存在, 请修改后重试.");
        }

        return insertSelective(user);
    }

    /**
     * 修改用户的方法
     *
     * @param user 用户对象
     * @return io.easyspring.demo.basis.rbac.model.User
     * Author summer
     * Version 2.0.0-RELEASE
     * DateTime 2019-10-15 15:34
     */
    @Override
    public User buildUpdate(User user) {

        // 检查除了当前数据以外是否还有相同的 用户名
        boolean valueExistWithoutSelf = valueExistWithoutSelf(User::getName,
                user.getName(), user.getId(), User.class);

        if (valueExistWithoutSelf) {
            throw new CommonException("用户名已存在, 请修改后重试.");
        }

        return buildUpdate(user);
    }

    /**
     * 根据传入的关键字和分页信息, 查询用户对象的分页数据
     *
     * @param keyWord 关键字
     * @param pageable 分页信息
     * @return com.github.pagehelper.Page<User>
     * Author summer
     * Version 2.0.0-RELEASE
     * DateTime 2019-10-15 15:15:03
     */
    @Override
    @SuppressWarnings("unchecked")
    public Page<User> findPageBuilder(String keyWord, Pageable pageable) {
        // 创建查询条件
        Weekend<User> weekend = likeWeekendBuild(keyWord, User.class,
                // TODO 2019-06-14 14:30 设置需要 like 匹配的字段
                User::getId);

        return findPage(weekend, pageable);
    }
}
